#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import datetime
from django.utils import simplejson
import cgi
import logging
import random

from model import StudentVoice
from model import ClassState
from model import Lecture


class MyHandler(webapp.RequestHandler):
    def get(self):
        studentVoice = None

    	# Get StudentVoice from DataStore or Create new 1
        lecture = Lecture.get(self.request.get('lectureKey'))
        classState = db.Query(ClassState).filter('lecture =', lecture).get()
        currTopic = classState.currentTopic

        userID = 0
        if self.request.get('userID') != 'null':
            userID = int(self.request.get('userID'))

        if userID != 0 and db.Query(StudentVoice).filter('userID =', userID).filter('topic =', currTopic).count() > 0:
            studentVoice = db.Query(StudentVoice).filter('userID =', userID).filter('topic =', currTopic)[0]
        elif userID != 0:
            studentVoice = StudentVoice(topic = currTopic, userID = userID)
        else:
            studentVoice = StudentVoice(topic = currTopic, userID = int(random.random() * 100000))

        if self.request.get('understand') == 'true':
            studentVoice.understand = True
        else:
            studentVoice.understand = False

        studentVoice.put()

        
        self.response.out.write(str(studentVoice.userID))
def main():
    logging.getLogger().setLevel(logging.DEBUG)
    app = webapp.WSGIApplication([
        (r'.*', MyHandler)], debug=True)
    wsgiref.handlers.CGIHandler().run(app)

if __name__ == "__main__":
    main()
